package examples.distributedsession;

import examples.distributedsession.support.ZooKeeperHelper;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author Bill
 * @version 2013-05-28
 */
public abstract class DistributedSessionFilter implements Filter {
    private static Logger logger = LoggerFactory.getLogger(DistributedSessionFilter.class);

    /**参数配置*/
    protected Configuration    conf;
    /**Session管理器*/
    protected SessionManager   sessionManager;
    /**初始化参数名称*/
    public static final String SERVERS  = "servers";
    public static final String TIMEOUT  = "timeout";
    public static final String POOLSIZE = "poolsize";

    /**
     * 初始化
     * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        conf = new Configuration();
        String servers = filterConfig.getInitParameter(SERVERS);
        if (StringUtils.isNotBlank(servers)) {
            conf.setServers(servers);
        }
        String timeout = filterConfig.getInitParameter(TIMEOUT);
        if (StringUtils.isNotBlank(timeout)) {
            try {
                conf.setTimeout(Long.valueOf(timeout));
            } catch (NumberFormatException ex) {
                logger.error("timeout parse error[" + timeout + "].");
            }
        }
        String poolsize = filterConfig.getInitParameter(POOLSIZE);
        if (StringUtils.isNotBlank(poolsize)) {
            try {
                conf.setPoolSize(Integer.valueOf(poolsize));
            } catch (NumberFormatException ex) {
                logger.error("poolsize parse error[" + poolsize + "].");
            }
        }
        //初始化ZooKeeper配置参数
        ZooKeeperHelper.initialize(conf);
    }

    /**
     * 销毁
     * @see javax.servlet.Filter#destroy()
     */
    @Override
    public void destroy() {
        if (sessionManager != null) {
            try {
                sessionManager.stop();
            } catch (Exception e) {
                logger.error("", e);
            }
        }
        //销毁ZooKeeper
        ZooKeeperHelper.destroy();
        logger.debug("DistributedSessionFilter.destroy completed.");
    }

    //在filter中需要关注的重点是doFilter方法。
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException,
            ServletException {
        // Jetty容器的Request对象包装器，用于重写Session的相关操作
        DSHttpServletRequestWrapper req = new DSHttpServletRequestWrapper((HttpServletRequest) request);
        chain.doFilter(req, response);
    }

    public class Configuration {
        public void setPoolSize(Integer integer) {
            //To change body of created methods use File | Settings | File Templates.
        }

        public void setTimeout(Long aLong) {
            //To change body of created methods use File | Settings | File Templates.
        }

        public void setServers(String servers) {
            //To change body of created methods use File | Settings | File Templates.
        }
    }

    private class SessionManager {
        public void stop() {
            //To change body of created methods use File | Settings | File Templates.
        }
    }
}